import request from '@/utils/http'

// 事业部响应（与后端 DeptResponse 对齐）
export interface DeptResponse {
  id?: number
  dept_name: string
  dept_code: string
  descriptions?: string | null
  status?: boolean
  parent_id?: number | null
  parent_name?: string | null
  parent_code?: string | null
  manager_id?: number | null
  manager_name?: string | null
  create_time?: string
  update_time?: string
}

// 列表响应
export interface DeptListResponse {
  total: number
  items: DeptResponse[]
  page: number
  size: number
  pages: number
}

// 树节点与树响应
export interface DeptTreeNode {
  id: number
  dept_name: string
  dept_code: string
  status?: boolean
  parent_id?: number | null
  manager_id?: number | null
  manager_name?: string | null
  children: DeptTreeNode[]
}

export interface DeptTreeResponse {
  items: DeptTreeNode[]
}

// 创建/更新请求体
export interface DeptCreate {
  dept_name: string
  dept_code: string
  descriptions?: string | null
  status?: boolean
  parent_id?: number | null
  parent_name?: string | null
  parent_code?: string | null
  manager_id?: number | null
  manager_name?: string | null
}

export interface DeptUpdate {
  dept_name?: string
  dept_code?: string
  descriptions?: string | null
  status?: boolean
  parent_id?: number | null
  parent_name?: string | null
  parent_code?: string | null
  manager_id?: number | null
  manager_name?: string | null
}

// 查询参数（与后端 DeptQuery 对齐），注意 current 是 page 的别名
export interface DeptQuery {
  current?: number
  size?: number
  dept_name?: string
  dept_code?: string
  status?: boolean
  keyword?: string
}

/**
 * 创建事业部
 */
export function createDept(params: DeptCreate) {
  return request.post<DeptResponse>({
    url: '/system/depts/create',
    params,
    showSuccessMessage: true
  })
}

/**
 * 获取事业部列表（分页）
 */
export function fetchDeptList(params: DeptQuery) {
  return request.post<DeptListResponse>({
    url: '/system/depts/list',
    params
  })
}

/**
 * 更新事业部
 */
export function updateDept(deptId: number, params: DeptUpdate) {
  return request.put<DeptResponse>({
    url: `/system/depts/${deptId}`,
    params,
    showSuccessMessage: true
  })
}

/**
 * 删除事业部
 */
export function deleteDept(deptId: number) {
  return request.del<{ message: string }>({
    url: `/system/depts/${deptId}`,
    showSuccessMessage: true
  })
}

/**
 * 获取事业部树
 */
export function fetchDeptTree(status?: boolean) {
  const params = typeof status === 'boolean' ? { status } : undefined
  return request.get<DeptTreeResponse>({
    url: '/system/depts/tree',
    params
  })
}